import { Vec3 } from 'cc';
import { BaseState } from './BaseState';

/**
 * AI逃跑状态
 * 
 * 功能：
 * 1. 计算逃跑路径
 * 2. 寻找安全位置
 * 3. 处理逃跑策略
 * 4. 管理逃跑行为
 * 
 * 特点：
 * 1. 智能躲避
 * 2. 安全点评估
 * 3. 动态路径调整
 * 4. 紧急避险
 */
export class FleeState extends BaseState {
    private fleeDistance: number = 15;
    private safeDistance: number = 20;
    private updatePathInterval: number = 0.5;
    private pathTimer: number = 0;

    public enter(): void {
        this.updateFleePath();
    }

    public exit(): void {
        this.controller.stopMoving();
    }

    public update(dt: number): void {
        const threat = this.controller.getTarget();
        if (!threat) {
            this.controller.changeState('idle');
            return;
        }

        const distance = Vec3.distance(this.controller.getPosition(), threat.position);
        if (distance > this.safeDistance) {
            this.controller.changeState('idle');
            return;
        }

        // 定期更新逃跑路径
        this.pathTimer += dt;
        if (this.pathTimer >= this.updatePathInterval) {
            this.pathTimer = 0;
            this.updateFleePath();
        }
    }

    private updateFleePath(): void {
        const threat = this.controller.getTarget();
        if (!threat) return;

        // 计算逃跑方向（远离威胁）
        const direction = new Vec3();
        Vec3.subtract(direction, this.controller.getPosition(), threat.position);
        direction.normalize();

        // 设置逃跑目标点
        const fleeTarget = new Vec3();
        Vec3.multiplyScalar(fleeTarget, direction, this.fleeDistance);
        Vec3.add(fleeTarget, fleeTarget, this.controller.getPosition());

        this.controller.moveTowards(fleeTarget);
    }
} 